package handler;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.StringTokenizer;

import model.Album;
import model.Artist;
import model.Music;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;

/**
 * Class allowing to provide some useful functions
 * @author jean
 *
 */
public class Utilities {
	
	/**
	 * Pathname to music media
	 */
	final String MEDIA_PATH = new String("/sdcard");
	
	/**
	 * Method allowing to have the remaining music to play.
	 * @param list		The initial list of music
	 * @param position	The position to start the list
	 * @return
	 */
	public ArrayList<Music> getSongsToPlay(ArrayList<Music> list, int position) {
		ArrayList<Music> res = new ArrayList<Music>();
		for(int i=position;i<list.size();i++) {
			res.add(list.get(i));
		}
		return res;
	}
	
	/**
	 * Method allowing to know if the database created or not.
	 * @param context
	 * @param dbName
	 * @return
	 */
	public boolean checkDataBase(Context context, String dbName) {
	    SQLiteDatabase checkDB = null;
	    try {
	        checkDB = SQLiteDatabase.openDatabase(context.getDatabasePath(dbName).getPath(), null,
	                SQLiteDatabase.OPEN_READONLY);
	        checkDB.close();
	    } catch (SQLiteException e) {
	        // database doesn't exist yet.
	    }
	    return checkDB != null ? true : false;
	}
	
	/**
	 * Method allowing to have an HashMap from Music, used for the Adapter
	 * @param m
	 * @param ar
	 * @param al
	 * @return
	 */
	public HashMap<String, String> MusicToHashMap(Music m, Artist ar, Album al) {
		
		HashMap<String, String> hm = new HashMap<String, String>();
		
		hm.put("title", m.getTitle());
		hm.put("artist", ar.getName());
		
		return hm;
		
	}
	
	/**
	 * Method allowing to have an HashMap from Artist, used for the Adapter
	 * @param a
	 * @return
	 */
	public HashMap<String, String> ArtistToHashMap(Artist a) {
		
		HashMap<String, String> hm = new HashMap<String, String>();
		hm.put("artist", a.getName());
		
		return hm;
		
	}
	
	/**
	 * Method allowing to have an HashMap from Album, used for the Adapter
	 * @param a
	 * @return
	 */
	public HashMap<String, String> AlbumToHashMap(Album a) {
		
		HashMap<String, String> hm = new HashMap<String, String>();
		hm.put("album", a.getName());
		
		return hm;
		
	}
	
	/**
	 * Function to convert milliseconds time to Hours:Minutes:Seconds
	 * @param milliseconds
	 * @return
	 */
	public String milliSecondsToTimer(long milliseconds){
		String finalTimerString = "";
		String secondsString = "";
		
	   // Convert total duration into time
	   int hours = (int)( milliseconds / (1000*60*60));
	   int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
	   int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
	   // Add hours if there
	   if(hours > 0){
		   finalTimerString = hours + ":";
	   }
	   
	   // Prepending 0 to seconds if it is one digit
	   if(seconds < 10){ 
		   secondsString = "0" + seconds;
	   }else{
		   secondsString = "" + seconds;}
	   
	   finalTimerString = finalTimerString + minutes + ":" + secondsString;
	
		// return timer string
		return finalTimerString;
	}
	
	/**
	 * Function to get Progress percentage
	 * @param currentDuration
	 * @param totalDuration
	 * */
	public int getProgressPercentage(long currentDuration, long totalDuration){
		Double percentage = (double) 0;
		
		long currentSeconds = (int) (currentDuration / 1000);
		long totalSeconds = (int) (totalDuration / 1000);
		
		// calculating percentage
		percentage =(((double)currentSeconds)/totalSeconds)*100;
		
		// return percentage
		return percentage.intValue();
	}

	/**
	 * Function to change progress to timer
	 * @param progress - 
	 * @param totalDuration
	 * returns current duration in milliseconds
	 * */
	public int progressToTimer(int progress, int totalDuration) {
		int currentDuration = 0;
		totalDuration = (int) (totalDuration / 1000);
		currentDuration = (int) ((((double)progress) / 100) * totalDuration);
		
		// return current duration in milliseconds
		return currentDuration * 1000;
	}
	
	/**
	 * Function to have a random playlist
	 * @param songsList
	 * returns songsListRandom
	 */
	
	public ArrayList<Music> toRandomPlaylist(ArrayList<Music> songsList, int numSong) {
		
		ArrayList<Music> songsListRandom = new ArrayList<Music>();
		int size = songsList.size();
		Random rand = new Random();
		int index;
		for(int i = 0;i<size;i++) {
			if(i==0) index = numSong;
			else if(i == (size-1)) index = 0;
			else index = rand.nextInt(songsList.size() - 1);
			songsListRandom.add(songsList.get(index));
			songsList.remove(index);
		}
		return songsListRandom;
	}
	
	/**
	 * Function allowing to have a Bitmap from byte[]
	 * @param blob
	 * @return Bitmap
	 */
	public Bitmap byteToBitmap(byte[] blob) {
		if(blob != null) {
			Bitmap bmp=BitmapFactory.decodeByteArray(blob,0,blob.length);
			return bmp;
		} else return null;
	}
	
	/**
	 * Put an Array of Integer in the SharedPreferences
	 * @param context
	 * @param key
	 * @param values
	 */
	public void setIntArrayPref(Context context, String key, ArrayList<Integer> values) {
	    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
	    prefs.edit().clear();
		int[] list = new int[10];
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < list.length; i++) {
		    str.append(list[i]).append(",");
		}
		prefs.edit().putString(key, str.toString());
		prefs.edit().commit();
	}
	
	/**
	 * Get an Array of Integer from the SharedPreferences
	 * @param context
	 * @param key
	 * @return int[]
	 */
	public int[] getIntArrayPref(Context context, String key) {
	    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
	    String savedString = prefs.getString(key, null);
	    if(savedString == null) return null;
	    StringTokenizer st = new StringTokenizer(savedString, ",");
	    int[] savedList = new int[10];
	    for (int i = 0; i < 10; i++) {
	        savedList[i] = Integer.parseInt(st.nextToken());
	    }
	    
	   return savedList;
	}
	
	/**
	 * Method allowing to have an Array of Int from an Array of Music, recording the id of Music.
	 * @param am
	 * @return
	 */
	public ArrayList<Integer> setArrayMusicToArrayInt(ArrayList<Music> am) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		for(int i=0;i<am.size();i++) {
			list.add(am.get(i).getId());
		}
		return list;
	}
	
	/**
	 * Method allowing to have all mp3 pathname on sdcard and save it in an ArrayList of HashMap
	 * @param path
	 * @return ArrayList<HashMap<String, String>>, filename and pathname of all mp3 file on sd card.
	 */
	public ArrayList<HashMap<String, String>> getAllFileOnSdCard(String path) {
		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		File home = new File(path);
		if (home.listFiles(new FileFilter()).length > 0) {
			for (File file : home.listFiles(new FileFilter())) { 
				if(file.isDirectory()) list.addAll(getAllFileOnSdCard(file.getPath()));
				else {
					HashMap<String, String> hm = new HashMap<String, String>();
					hm.put("filename", file.getName());
					hm.put("pathname", file.getPath());
					list.add(hm);
				}
			}
		}
		list.trimToSize();
		return list;
	}
	
	/**
	 * Override to simplify calls...
	 * @return
	 */
	public ArrayList<HashMap<String, String>> getAllFileOnSdCard() {
		return getAllFileOnSdCard(MEDIA_PATH);
	}
}
